$.reload = function () {
    location.reload();
    return false;
}
$.request = function (name) {
    var search = location.search.slice(1);
    if(search.indexOf("url") >= 0){
          var url= search.substring(search.lastIndexOf("url")+4);//获取取url路径
          return  url;
    }
    var arr = search.split("&");
    for (var i = 0; i < arr.length; i++) {
        var ar = arr[i].split("=");
        if (ar[0] == name) {
            if (unescape(ar[1]) == 'undefined') {
                return "";
            } else {
                return unescape(ar[1]);
            }
        }
    }
    return "";
}
$.loading = function (bool, text) {
    var $loadingpage = top.$("#loadingPage");
    var $loadingtext = $loadingpage.find('.loading-content');
    if (bool) {
        $loadingpage.show();
    } else {
        if ($loadingtext.attr('istableloading') == undefined) {
            $loadingpage.hide();
        }
    }
    if (!!text) {
        $loadingtext.html(text);
    } else {
        $loadingtext.html("数据加载中，请稍后…");
    }
    $loadingtext.css("left", (top.$('body').width() - $loadingtext.width()) / 2 - 50);
    $loadingtext.css("top", (top.$('body').height() - $loadingtext.height()) / 2);
}
$.modalOpen = function (options) {
    var defaults = {
        id: null,
        type: 2,
        title: '系统窗口',
        width: "300px",
        height: "400px",
        url: '',
        shade: 0.3,
        btn: ['确认', '关闭'],
        btnclass: ['btn btn-primary', 'btn btn-danger'],
        callBack: null,
        callBacks: null,
        maxmin: true,
        minmin: false,
        full: false,
        closeBtn: 1, // 关闭按钮
        skin: 'layui-layer-molv', //样式类名
    };
    var options = $.extend(defaults, options);
    var _width = top.$(window).width() > parseInt(options.width.replace('px', '')) ? options.width : top.$(window).width() + 'px';
    var _height = top.$(window).height() > parseInt(options.height.replace('px', '')) ? options.height : top.$(window).height() + 'px';

    var vuel = options.url;
    //options.type == 0,1 时 页面为本页面元素。
    if (options.type != 0 && options.type != 1) {
        var cp_timestamp = new Date().getTime();
        if (vuel.indexOf("?") > 0)
            vuel = vuel + "&v=" + cp_timestamp;
        else
            vuel = vuel + "?v=" + cp_timestamp;
    }
    var auto = true;//是否使用响应式，使用百分比时，应设置为false
    if (_width.indexOf("%") >= 0 || _height.indexOf("%") >= 0) {
        auto = false;
    }

    var layerOp = top.layer.open({
        id: options.id,
        type: options.type,
        shade: options.shade,
        closeBtn: options.closeBtn,
        title: options.title,
        fix: false,
        auto: auto,
        area: [_width, _height],
        maxmin: options.maxmin,
        minmin: options.minmin,
        content: vuel,
        btn: options.btn,
        moveOut: true,
        btnclass: options.btnclass,
        yes: function () {
            options.callBack(options.id)
        }, cancel: function () {
            return true;
        }, btn2: function () {
            if (options.callBacks != null) {
                options.callBacks(options.id);
                return false;
            }
        }
    });
    if (options.full) {
        layer.full(layerOp);
    }


}
$.modalClose = function () {
    var index = top.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
    var $IsdialogClose = top.$("#layui-layer" + index).find('.layui-layer-btn').find("#IsdialogClose");
    var IsClose = $IsdialogClose.is(":checked");
    if ($IsdialogClose.length == 0) {
        IsClose = true;
    }
    if (IsClose) {
        top.layer.close(index);
    } else {
        location.reload();
    }
}
$.currentWindow = function () {
    var iframeId = top.$(".NFine_iframe:visible").attr("id");
    return top.frames[iframeId];
}
$.modalConfirm = function (content, callBack, btns) {
    if (!btns) {
        btns = ['确认', '取消'];
    }
    var lock = false; //默认未锁定
    var myconfirm = top.layer.confirm(content, {
        icon: "fa-exclamation-circle",
        title: "系统提示",
        btn: btns,
        btnclass: ['btn btn-primary', 'btn btn-danger']
    }, function () {
        if (!lock) {
            lock = true; // 锁定
            callBack(true);
        }
        layer.close(myconfirm);
    }, function () {
        callBack(false)
        //layer.close(myconfirm);
    });
}
$.modalAlert = function (content, type) {
    var icon = "";
    if (type == 'success') {
        icon = "fa-check-circle";
    }
    if (type == 'error') {
        icon = "fa-times-circle";
    }
    if (type == 'warning') {
        icon = "fa-exclamation-circle";
    }
    top.layer.alert(content, {
        icon: icon,
        title: "系统提示",
        btn: ['确认'],
        btnclass: ['btn btn-primary'],
    });
}
$.modalMsg = function (content, type) {
    if (type != undefined) {
        var icon = "";
        if (type == 'success') {
            icon = "fa-check-circle";
        }
        if (type == 'error') {
            icon = "fa-times-circle";
        }
        if (type == 'warning') {
            icon = "fa-exclamation-circle";
        }
        top.layer.msg(content, { icon: icon, time: 4000, shift: 5 });
        top.$(".layui-layer-msg").find('i.' + icon).parents('.layui-layer-msg').addClass('layui-layer-msg-' + type);
    } else {
        top.layer.msg(content);
    }
}
$.submitForm = function (options) {
    var defaults = {
        url: "",
        param: [],
        loading: "正在提交数据...",
        success: null,
        close: true,
        dataType: "json",
        contentType: "application/x-www-form-urlencoded",
        paramType: false
    };
    var options = $.extend(defaults, options);
    $.loading(true, options.loading);
    window.setTimeout(function () {
        if ($('[name=__RequestVerificationToken]').length > 0) {
            options.param["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val();
        }
        var _data = options.param;
        if (options.paramType) {
            _data = JSON.stringify(options.param); //[FromBody]
            options.contentType = "application/json";
        }
        $.ajax({
            url: options.url,
            type: "post",
            dataType: options.dataType,
            data: _data,
            contentType: options.contentType,
            success: function (data) {
                $.loading(false);
                if (data.state == "success") {
                    options.success(data);
                    $.modalMsg(data.message, "success");
                    if (options.close == true) {
                        $.modalClose();
                    }
                } else {
                    $.modalMsg(data.message, "warning");
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $.loading(false);
                $.modalMsg(errorThrown, "error");
            },
            beforeSend: function (jqXHR) {
                $.loading(true, options.loading);
                jqXHR.setRequestHeader("Authorization", 'Bearer ' + window.LS.get("lmgcmstoken"));
            },
            complete: function () {
                $.loading(false);
            }
        });
    }, 500);
}
$.deleteForm = function (options) {
    var defaults = {
        prompt: "注：您确定要删除该项数据吗？",
        loading: "正在删除数据...",
        url: "",
        param: [],
        dataType: "json",
        contentType: "application/x-www-form-urlencoded",
        paramType: false,
        success: null,
        close: true
    };
    var options = $.extend(defaults, options);
    if ($('[name=__RequestVerificationToken]').length > 0) {
        options.param["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val();
    }
    $.modalConfirm(options.prompt, function (r) {
        if (r) {
            $.loading(true, options.loading);
            window.setTimeout(function () {
                var _data = options.param;
                if (options.paramType) {
                    _data = JSON.stringify(options.param); //[FromBody]
                    options.contentType = "application/json";
                }
                $.ajax({
                    url: options.url,
                    type: "post",
                    dataType: options.dataType,
                    data: _data,
                    contentType: options.contentType,
                    success: function (data) {
                        if (data.state == "success") {
                            options.success(data);
                            $.modalMsg(data.message, data.state);
                        } else {
                            $.modalMsg(data.message, data.state);
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        $.loading(false);
                        $.modalMsg(errorThrown, "error");
                    },
                    beforeSend: function (jqXHR) {
                        $.loading(true, options.loading);
                        jqXHR.setRequestHeader("Authorization", 'Bearer ' + window.LS.get("lmgcmstoken"));
                    },
                    complete: function () {
                        $.loading(false);
                    }
                });
            }, 500);
        }
    });
}
/** select2 */
$.fn.bindSelect = function (options) {
    var defaults = {
        id: "id",
        text: "text",
        search: false,
        url: "",
        param: [],
        change: null
    };
    var options = $.extend(defaults, options);
    var $element = $(this);
    if (options.url != "") {
        $.ajax({
            url: options.url,
            data: options.param,
            dataType: "json",
            async: false,
            success: function (data) {
                $.each(data, function (i) {
                    $element.append($("<option></option>").val(data[i][options.id]).html(data[i][options.text]));
                });
                $element.select2({
                    minimumResultsForSearch: options.search == true ? 0 : -1,
                    language: 'zh-CN'
                });
                $element.on("change", function (e) {
                    if (options.change != null) {
                        options.change(data[$(this).find("option:selected").index()]);
                    }
                    $("#select2-" + $element.attr('id') + "-container").html($(this).find("option:selected").text().replace(/　　/g, ''));
                });
            },
            beforeSend: function (jqXHR) {
                jqXHR.setRequestHeader("Authorization", 'Bearer ' + window.LS.get("lmgcmstoken"));
            }
        });
    } else {
        $element.select2({
            minimumResultsForSearch: -1
        });
    }
}
//自定义函数处理queryParams的批量增加
$.fn.serializeJsonObject = function () {
    var json = {};
    var form = this.serializeArray();
    $.each(form, function () {
        if (json[this.name]) {
            if (!json[this.name].push) {
                json[this.name] = [json[this.name]];
            }
            json[this.name].push();
        } else {
            json[this.name] = this.value || '';
        }
    });
    return json;
}
$.fn.formValid = function () {
    return $(this).valid({
        errorPlacement: function (error, element) {
            element.parents('.formValue').addClass('has-error');
            element.parents('.has-error').find('i.error').remove();
            element.parents('.has-error').append('<i class="form-control-feedback fa fa-exclamation-circle error" data-placement="left" data-toggle="tooltip" title="' + error + '"></i>');
            $("[data-toggle='tooltip']").tooltip();
            if (element.parents('.input-group').hasClass('input-group')) {
                element.parents('.has-error').find('i.error').css('right', '33px')
            }
        },
        success: function (element) {
            element.parents('.has-error').find('i.error').remove();
            element.parent().removeClass('has-error');
        }
    });
}
$.fn.formSerialize = function (formdate) {
    var element = $(this);
    if (!!formdate) {
        for (var key in formdate) {
            var $id = element.find('#' + key);
            var value = $.trim(formdate[key]).replace(/&nbsp;/g, '');
            var type = $id.attr('type');
            if ($id.hasClass("select2-hidden-accessible")) {
                type = "select";
            }
            switch (type) {
                case "checkbox":
                    if (value == "true") {
                        $id.attr("checked", 'checked');
                    } else {
                        $id.removeAttr("checked");
                    }
                    break;
                case "select":
                    $id.val(value).trigger("change");
                    break;
                default:
                    $id.val(value);
                    break;
            }
        };
        return false;
    }
    var postdata = {};
    element.find('input,select,textarea').each(function (r) {
        var $this = $(this);
        var id = $this.attr('id');
        var type = $this.attr('type');
        var multiple = $this.attr('multiple');
        switch (type) {
            case "checkbox":
                postdata[id] = $this.is(":checked");
                break;
            default:
                var value = $this.val() == "" ? "&nbsp;" : $this.val();
                if (multiple != "multiple") {
                    if (value && value.length == 1) {
                        if (!$.request("keyValue")) {
                            value = value ? value.replace(/&nbsp;/g, '') : "";
                        }
                    }
                    if (value)
                        value = value.replace(/&nbsp;/g, '');
                }
                postdata[id] = value;
                break;
        }
    });
    if ($('[name=__RequestVerificationToken]').length > 0) {
        postdata["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val();
    }
    return postdata;
};
$.fn.authorizeButton = function () {
    var moduleId = top.$(".NFine_iframe:visible").attr("id").substr(6);
    var dataJson = top.clients.authorizeButton[moduleId];
    var userId = top.clients.user.AccountId;
    //console.log(userId);
    if (userId != "admin") {
        var $element = $(this);
        $element.find('a[authorize=yes]').attr('authorize', 'no');
        if (dataJson != undefined) {
            $.each(dataJson, function (i) {
                $element.find("#" + dataJson[i].DomId).attr('authorize', 'yes');
            });
        }
        $element.find("[authorize=no]").parents('li').prev('.split').remove();
        $element.find("[authorize=no]").parents('li').remove();
        $element.find('[authorize=no]').remove();
    }
}
$.fn.dataGrid = function (options) {
    var defaults = {
        datatype: "json",
        autowidth: true,
        rownumbers: true,
        shrinkToFit: false,
        gridview: true,
        height: $(window).height() - 135,
        loadBeforeSend: function (jqXHR) {
            jqXHR.setRequestHeader("Authorization", 'Bearer ' + window.LS.get("lmgcmstoken"));
        },
    };
    var options = $.extend(defaults, options);
    var $element = $(this);
    options["onSelectRow"] = function (rowid) {
        var length = $(this).jqGrid("getGridParam", "selrow");
        var $operate = $(".operate");

        if (length != null) {
            if (length.length > 0) {
                $operate.animate({ "left": 0 }, 200);
            } else {
                $operate.animate({ "left": '-100.1%' }, 200);
            }
        } else {
            $operate.animate({ "left": '-100.1%' }, 200);
        }

        $operate.find('.close').click(function () {
            $operate.animate({ "left": '-100.1%' }, 200);
        })
    };
    $element.jqGrid(options);
};
$.fn.jqGridRowValue = function () {
    var $grid = $(this);
    var selectedRowIds = $grid.jqGrid("getGridParam", "selarrrow");
    if (selectedRowIds != "") {
        var json = [];
        var len = selectedRowIds.length;
        for (var i = 0; i < len; i++) {
            var rowData = $grid.jqGrid('getRowData', selectedRowIds[i]);
            json.push(rowData);
        }
        return json;
    } else {
        return $grid.jqGrid('getRowData', $grid.jqGrid('getGridParam', 'selrow'));
    }
}
$.jsonWhere = function (data, action) {
    if (action == null) return;
    var reval = new Array();
    $(data).each(function (i, v) {
        if (action(v)) {
            reval.push(v);
        }
    })
    return reval;
}

function selectOption(inputName, element, selectedValue) {
    if (selectedValue == undefined) {
        selectedValue = $(element).text();
    }
    $('#' + inputName).val(selectedValue);
}
function selectOption1(inputName, inputValue, element, selectedValue) {
    if (selectedValue == undefined) {
        selectedValue = $(element).text();
    }
    $('#' + inputName).val($(element).text());
    $('#' + inputValue).val(selectedValue);
}
/**
 * 弹出外键对应的数据字典表格
 *  mID 返回值绑定的VUE控件
 *  mName 返回名称的VUE控件
 *  tableName 数据字典对应的数据库表
 *  params [可选] 对象参数包括
 *  	[可选] 返回值选取的字段，参数设置{fields:{ID:'UID',NAME:'UNAME', IDTITLE:'ID', NAMETITLE:'名称'}} 默认{fields:{ID:'ID',NAME:'NAME'}}
 *  	[可选] 单选or多选，参数设置{radio:true} or {checkbox:true} 默认单选
 *  	[可选] 搜索条件 conditions  {radio:true,conditions:{FID:1,FNAME:'新闻公告'}}
 *  			使用whereStr直接拼接SQL查询条件，将不再接受其他条件 如{conditions:{whereStr:' 1=1 and (UNAME like \'%'+localStorage.UN+'%\''+' or GROUP_NAMES like \'%'+localStorage.UN+'%\')'}}
 *  	[可选] 直接使用sql语句进行查询
 *  			selectTable('stu_exam_place', 'stu_exam_place', 'DD_GROUP', {checkbox:true, search:'exam_place',  fields:{ID:'exam_place', NAME:'exam_place', NAMETITLE:'考场'}, sql: 'select distinct exam_place from dd_candidate'})
 *  	[可选] 其他表格要显示的字段 columns {radio:true,conditions:{FID:1,FNAME:'新闻公告'},columns:{FNAME:'父分类名称'}}
 *  	[可选] 窗口标题 title {radio:true,conditions:{FID:1,FNAME:'新闻公告'},columns:{FNAME:'父分类名称'},title:'操作'}
 *  	[可选] 搜索框搜索字段 { search: 'NAME'}
 *  	[可选] 排序 {  sort:'grade', order:'asc' }
 *  	[可选] 分页条数 {  pageSize:10 }
 *  	[可选] 多行的index { rowIndex: 'index'}
 *     
<div class="input-group" style="width:99%;">
    <input type="hidden" id="p_lxbmnum" name="p_lxbmnum" autocomplete="off" class="form-control">
    <input type="text" id="p_lxbm" name="p_lxbm" class="form-control">
    <div class="input-group-btn">
        <a href="" onclick="selectTable('p_lxbmnum', 'p_lxbm', 'Base_Branch', { conditions: {whereStr:'Bran_name=\'校领导\''}, search:'Bran_name',columns: { Bran_number:'ID',Bran_name: '名称' },fields:{Bran_number:'Bran_number',Bran_name:'Bran_name'}});" class="btn btn-default" style="height:35px;">
            <i class="glyphicon glyphicon-chevron-down"></i>
        </a>
    </div>
</div>
 */
function selectTable(mID, mName, tableName, params) {
    if (!params) params = {}
    var tableColumns = [];
    if (params.columns) {
        for (var key in params.columns) {
            tableColumns.push({ field: key, title: params.columns[key], sortable: true });
        }
    }
    var fields = params.fields || { ID: 'ID', NAME: 'NAME' };
    var showID = params.showID || 'N';
    if (showID == 'Y') {
        tableColumns.splice(0, 0, { field: fields.ID, title: fields.IDTITLE || 'ID' });
    }
    var radioOrcheckbox = { radio: true };
    if (params.checkbox) radioOrcheckbox = { checkbox: true };
    tableColumns.splice(0, 0, radioOrcheckbox);
    var conditions = JSON.stringify(params.conditions || { 1: '1' });
    sessionStorage.tableParams = JSON.stringify({
        mID: mID,
        mName: mName,
        search: params.search || 'NAME',
        tableName: tableName,
        fields: fields,
        tableColumns: tableColumns,
        searchField: params.searchField || 'NAME',
        conditions: conditions,
        sql: params.sql,
        showID: showID,
        sort: params.sort || 'ID',
        order: params.order || 'asc',
        pageSize: params.pageSize || 10,
        rowIndex: params.rowIndex,
        funcallBack: params.funcallBack || '',
    });

    var height = params.issm ? ' - 280px' : ' - 132px';
    params.issm = params.issm ? '' : 'modal-dialog-big';
    params.title = params.title || '操作';

    var str = '<div class="modal fade" id="tempSelectTableDiv">   <div class="modal-dialog ' + params.issm + '">       <div class="modal-content">        <div class="modal-header bg-primary" style="padding:10px;">        <button type="button" class="close" data-dismiss="modal" aria-label="Close">        <span aria-hidden="true"style="font-size: 20px;">×</span>    </button>    <h5 class="modal-title"><i class="fa fa-th-large fa-fw"></i> ' + params.title + '</h5>        </div>        <div class="modal-body">        <iframe src="'+RESOURCES_PATH+'/lib/tableSelector/tableSelector.html?funcallBack=' + params.funcallBack+'" frameborder="0" style="width:100%; height:calc(100vh' + height + ');">   </div></div></div> </div>';
    $('body').append(str);
    $('#tempSelectTableDiv').on('hidden.bs.modal', function () { $(this).remove(); }).modal('show');
    if (!!document.querySelector("#" + mName)) {
        document.querySelector("#" + mName).scrollIntoView(true);
    }
}
//扩展Date格式化
Date.prototype.Format = function (format) {
    var o = {
        "M+": this.getMonth() + 1, //月份           
        "d+": this.getDate(), //日           
        "h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, //小时           
        "H+": this.getHours(), //小时           
        "m+": this.getMinutes(), //分           
        "s+": this.getSeconds(), //秒           
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度           
        "S": this.getMilliseconds() //毫秒           
    };
    var week = {
        "0": "\u65e5",
        "1": "\u4e00",
        "2": "\u4e8c",
        "3": "\u4e09",
        "4": "\u56db",
        "5": "\u4e94",
        "6": "\u516d"
    };
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    if (/(E+)/.test(format)) {
        format = format.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "\u661f\u671f" : "\u5468") : "") + week[this.getDay() + ""]);
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return format;
};

function empty(e) {
    switch (e) {
        case "":
        case 0:
        case "0":
        case null:
        case false:
        case undefined:
            return true;
        default:
            return false;
    }
}
function judgeUrl(url) {
    if (url.indexOf("http://") == 0 || url.indexOf("https://") == 0) {
        return true;
    }
    return false;
}